package cn.koala.key.stock.service.impl;

import cn.koala.key.api.KeyManagementApi;
import cn.koala.key.common.feign.FeignUtils;
import cn.koala.key.common.utils.OrderNoGenerator;
import cn.koala.key.entity.LeaveStock;
import cn.koala.key.entity.enums.OrderTypeEnum;
import cn.koala.key.stock.domain.dto.LeaveStockDTO;
import cn.koala.key.stock.domain.dto.StockSearch;
import cn.koala.key.stock.service.LeaveStockService;
import cn.seed.common.core.*;
import org.springframework.stereotype.Service;

/**
 * 出库业务
 * @description
 * @author shuai.xu
 * @time 2019/5/5 9:42
*/
@Service
public class LeaveStockServiceImpl implements LeaveStockService {

    @Override
    public Result<ResultList<LeaveStock>> list(StockSearch leaveStockSearch) {
        return FeignUtils.getHttpApi(KeyManagementApi.class).leaveStockList(leaveStockSearch);
    }

    @Override
    public Result insertOrUpdate(LeaveStockDTO leaveStockDTO) {
        String orderNo = null;
        if (leaveStockDTO.getLeaveStock().getId() == null){
            //生成出库单
            orderNo = OrderNoGenerator.generateOrderNo(0000,OrderNoGenerator.ORDER_TYPE_LEAVE);
            leaveStockDTO.getLeaveStock().setOrderNo(orderNo);
        }else {
            orderNo = leaveStockDTO.getLeaveStock().getOrderNo();
        }
        //获取钥匙数量
        leaveStockDTO.getLeaveStock().setKeyCount(leaveStockDTO.getLeaveStockDetailList().size());
        //初始化出库单明细
        String finalOrderNo = orderNo;
        leaveStockDTO.getLeaveStockDetailList().stream().forEach(enterStockDetail -> {
            enterStockDetail.setOrderNo(finalOrderNo);
            enterStockDetail.setIsDeleted(OrderTypeEnum.KEY_NO_DELETE.getValue());
            enterStockDetail.setIsStorage(OrderTypeEnum.KEY_OUT_STORE.getValue());
        });
        return FeignUtils.getHttpApi(KeyManagementApi.class).insertOrUpdateLeaveStock(leaveStockDTO);
    }

    @Override
    public Result invalidOrOutStock(String orderNo, Integer status) {
        //更新出库单状态
        return FeignUtils.getHttpApi(KeyManagementApi.class).invalidOrOutStock(orderNo,status);
    }
}
